#include "Ship.h"
#include <iostream>

Ship::Ship(TypeOfShip _type, int _x, int _y, Rotation _rotation)
:m_type(_type)
{
	int dx, dy ,length;
	//calculate dx,dy
	if (_rotation == HORIZONTAL)
	{
		dx = 0;
		dy = 1;
	}
	else if (_rotation == VERTICAL)
	{
		dx = 1;
		dy = 0;
	}


	//calculate m_pos
	// positions of elements of ship
	m_pos.clear();
	
	length = GetLength(_type);
	m_count = length;
	for (int i=0;i<length;i++)
	{
		m_pos.insert(Point(_x,_y));
		_x += dx;
		_y += dy;
	}
}

Ship::~Ship()
{
	m_pos.clear();
}

PointSet Ship::GetSpaceForShip()
{
	PointSet result;
	PointSet::iterator ii;
	for (ii=m_pos.begin();ii != m_pos.end(); ii++)
	{
		Point p = *ii;
		result.insert(Point(p.first,p.second));
		result.insert(Point(p.first,p.second+1));
		result.insert(Point(p.first,p.second-1));
		result.insert(Point(p.first+1,p.second));
		result.insert(Point(p.first-1,p.second));
	}
	return result;
}

PointSet Ship::GetPos()
{
	return m_pos;
}

//return type of ship
Ship::TypeOfShip Ship::GetType()
{
	return m_type;
}

//Get length of ship
int Ship::GetLength(TypeOfShip _type)
{
	int length = 0;
	// calculate length
	switch (_type)
	{
	case DESTROYER:
		length = 2;
		break;
	case PATROL:
		length = 3;
		break;
	case SUBMARINE:
		length = 3;
		break;
	case BATTLE:
		length = 4;
		break;
	case AIRCRAFT:
		length = 5;
		break;
	}
	return length;
}
//end

//shot a ship
bool Ship::Shot(Point p)
{
	if (m_pos.find(p) != m_pos.end())
	{
		m_count --;
		if (m_count < 0)
		{
			std::cout << "ERROR, m_count" << std::endl;
		}
		return true;
	}
	return false;
}
//end

//check a ship destroyed
bool Ship::IsDestroyed()
{
	return m_count == 0;
}